// subPages/business/shop/shop.js
const app = getApp()
var util =  require('../../../utils/util.js');
var flag = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    region: ['请选择', '请选择'],
    customItem: '请选择',
    evalList: [{ tempFilePaths: [], imgList: [] }],
    downImg: '/resources/business/down2.png',
    upImg: '/resources/business/up2.png',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.setData({
      regionImgSrc: that.data.downImg,
      startTimeImgSrc: that.data.downImg,
      endTimeImgSrc: that.data.downImg,
      shopType: app.globalData.shopType
    })
    that.getData(that.getUrl())
  },

  //获取url
  getUrl:function(){
    var urlType = ''
    switch (app.globalData.shopType) {
      case '0':
        urlType = 'get_community_service_shop_content'
        break;
      case '1':
        urlType = 'admin_get_community_health_shop_content'
        break;
      case '2':
        urlType = 'get_kitchen_content'
        break;
    }
    return urlType
  },

  //获取数据
  getData:function(urlType){
    var that = this
    util.getAjax(`${app.globalData.apiUrl}/${urlType}`,function(res){
      console.log(res)
      if(res.data){
        switch (that.data.shopType) {
          case '0':
            var img = res.data.head_img.replace('http:','https:');
            var imgs = []
            imgs.push(img)
            that.setData({
              name: res.data.shop_name,
              phone: res.data.shop_phone,
              announcement: res.data.gg,
              address: res.data.address,
              rule: res.data.up_pay,
              isStartTime: res.data.open_time?true:false,
              isEndTime: res.data.close_time?true:false,              
              startTime: res.data.open_time,
              endTime: res.data.close_time,
              evalList: [{ tempFilePaths: [], imgList: imgs }],
            })
            var getDataJson = []
            getDataJson.push(that.data.name,that.data.phone,that.data.announcement,that.data.address,that.data.rule,that.data.startTime,that.data.endTime,imgs)
            that.setData({
              getDataJson: JSON.stringify(getDataJson)
            })
            break;
          case '1':
            var img = res.data.shop_img.replace('http:','https:');
            var imgs = []
            imgs.push(img)
            that.setData({
              name: res.data.shop_name,
              phone: res.data.shop_phone,
              address: res.data.address,
              introduce: res.data.content,
              isRegion: true,
              region: [res.data.sheng,res.data.shi],
              evalList: [{ tempFilePaths: [], imgList: imgs }],
            })
            var getDataJson = []
            getDataJson.push(that.data.name,that.data.phone,that.data.address,that.data.region,that.data.introduce,imgs)
            that.setData({
              getDataJson: JSON.stringify(getDataJson)
            })
            break;
          case '2':
            var img = res.data.head_img.replace('http:','https:');
            var imgs = []
            imgs.push(img)
            that.setData({
              name: res.data.name,
              phone: res.data.phone,
              evalList: [{ tempFilePaths: [], imgList: imgs }],
            })
            var getDataJson = []
            getDataJson.push(that.data.name,that.data.phone,imgs)
            that.setData({
              getDataJson: JSON.stringify(getDataJson)
            })
            break;
        }
      }
    },{id: app.globalData.shopId})
  },

  //地区选择
  bindRegionChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value,
      isRegion: true,
      regionImgSrc: this.data.downImg
    })
  },

  bindRegionCancel:function(){
    this.setData({
      regionImgSrc: this.data.downImg
    })
  },

  bindStartTimeChange:function(){
    this.setData({
      startTime: e.detail.value,
      isStartTime: true,
      startTimeImgSrc: this.data.downImg
    })
  },
  bindStartTimeCancel:function(){
    this.setData({
      startTimeImgSrc: this.data.downImg
    })
  },
  bindEndTimeChange:function(){
    this.setData({
      endTime: e.detail.value,
      isEndTime: true,
      endTimeImgSrc: this.data.downImg
    })
  },
  bindEndTimeCancel:function(){
    this.setData({
      endTimeImgSrc: this.data.downImg
    })
  },

  //选择箭头
  imgChange:function(e){
    var that = this
    var type = e.currentTarget.dataset.type
    switch (type) {
      case 'region':
        if(that.data.regionImgSrc == that.data.downImg){
          that.setData({
            regionImgSrc: that.data.upImg
          })
        }
        break;
      case 'start':
        if(that.data.startTimeImgSrc == that.data.downImg){
          that.setData({
            startTimeImgSrc: that.data.upImg
          })
        }
        break;
      case 'end':
        if(that.data.endTimeImgSrc == that.data.downImg){
          that.setData({
            endTimeImgSrc: that.data.upImg
          })
        }
        break;
    }
  },
  
  //添加图片
  joinPicture: function (e) {
    var index = e.currentTarget.dataset.index;
    var evalList = this.data.evalList;
    var that = this;
    var imgNumber = evalList[index].tempFilePaths;
    if (imgNumber.length >= 1) {
      util.showModal('提示','最多上传四张图片')
      return;
    }
    wx.showActionSheet({
      itemList: ["从相册中选择", "拍照"],
      itemColor: "#f7982a",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage("album", imgNumber);
          } else if (res.tapIndex == 1) {
            that.chooseWxImage("camera", imgNumber);
          }
        }
      }
    })
  },

  //选择图片
  chooseWxImage: function (type, list) {
    var img = list;
    var len = img.length;
    var that = this;
    var evalList = this.data.evalList;
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: [type],
      success: function (res) {
        // console.log(res)
        var addImg = res.tempFilePaths;
        var addLen = addImg.length;
        if ((len + addLen) > 1) {
          for (var i = 0; i < (addLen - len); i++) {
            var str = {};
            str.pic = addImg[i];
            img.push(str);
          }
        } else {
          for (var j = 0; j < addLen; j++) {
            var str = {};
            str.pic = addImg[j];
            img.push(str);
          }
        }
        that.setData({
          evalList: evalList
        })
        that.upload(img);
      },
    })
  },

  //删除图片
  clearImg: function (e) {
    var that = this
    var index = e.currentTarget.dataset.index;
    var evalList = that.data.evalList;
    wx.request({
      url: app.globalData.apiUrl +'/Api/First/delete',
      data: {
        file: evalList[0].tempFilePaths[index]
      },
      method: 'get',
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        // console.log(res)
        if(res.data == 1){
          var img = evalList[0].tempFilePaths;
          var img2 = evalList[0].imgList;
          img.splice(index, 1);
          img2.splice(index, 1);          
          that.setData({
            evalList: evalList
          })
        }
      },
      fail: function (res) {
        console.log("失败",res);
      }
    })
  },

  //多张图片上传
  upload: function (path) {
    var that = this;
    var curImgList = [];
    for (var i = 0; i < path.length; i++) {
      wx.showToast({
        icon: "loading",
        title: "正在上传"
      }),
      wx.uploadFile({
        url: app.globalData.apiUrl + '/upload',//接口处理在下面有写
        filePath: path[i].pic,
        name: 'img',
        header: { "Content-Type": "multipart/form-data" },
        formData: {
          douploadpic: '1'
        },
        success: function (res) {
          // console.log(res)
          curImgList.push('https://jzj.freei.cc'+res.data);
          var evalList = that.data.evalList;
          evalList[0].imgList = curImgList;
          that.setData({
            evalList: evalList
          })
        },
        fail: function (e) {
          util.showModal('提示','上传失败')
          return
        },
        complete: function () {
          wx.hideToast();  //隐藏Toast
        }
      })
    }
  },

  //设置图片
  setImg:function(){
    var that = this 
    var evalList = that.data.evalList
    var imgStr = ''
    if(evalList){
      var imgList = evalList[0].imgList
      for (var j = 0; j < imgList.length; j++) {
        imgStr = imgList[j]
      }
    }
    // console.log(imgPort)
    return imgStr
  },

  formSubmit:function(e){
    // console.log(e)
    var that = this
    if(flag){
      return
    }
    flag = true
    switch (that.data.shopType) {
      case '0':
        var name = e.detail.value.name
        var phone = e.detail.value.phone
        var announcement = e.detail.value.announcement
        var address = e.detail.value.address
        var rule = e.detail.value.rule
        var startTime = e.detail.value.startTime
        var endTime = e.detail.value.endTime
        var img = that.setImg()
        if(name == '' || phone == '' || address == '' || announcement == '' || rule == '' || startTime == '' || endTime == '' || img == ''){
          util.showModal('提示','请填写完整信息')
          flag = false
          return 
        }
        var newDataJson = []
        newDataJson.push(name,phone,announcement,address,rule,startTime,endTime,img)
        if(that.data.getDataJson == JSON.stringify(newDataJson)){
          util.showModal('提示','请修改数据后，重新提交')
          flag = false
          return
        }
        that.save(newDataJson)
        break;
      case '1':
        var name = e.detail.value.name
        var phone = e.detail.value.phone
        var region = e.detail.value.region
        var address = e.detail.value.address
        var introduce = e.detail.value.introduce
        var img = that.setImg()
        for(var i in region){
          if(region[i] == '请选择'){
            util.showModal('提示','请选择店铺所在地区')
            flag = false
            return 
          }
        }
        if(name == '' || phone == '' || address == '' || introduce == '' || img == []){
          util.showModal('提示','请填写完整信息')
          flag = false
          return 
        }
        var newDataJson = []
        newDataJson.push(name,phone,address,region,introduce,img)
        if(that.data.getDataJson == JSON.stringify(newDataJson)){
          util.showModal('提示','请修改数据后，重新提交')
          flag = false
          return
        }
        that.save(newDataJson)
        break;
      case '2':
        var name = e.detail.value.name
        var phone = e.detail.value.phone
        var img = that.setImg()
        if(name == '' || phone == ''|| img == []){
          util.showModal('提示','请填写完整信息')
          flag = false
          return 
        }
        var newDataJson = []
        newDataJson.push(name,phone,img)
        if(that.data.getDataJson == JSON.stringify(newDataJson)){
          util.showModal('提示','请修改数据后，重新提交')
          flag = false
          return
        }
        that.save(newDataJson)
        break;
    }
  },

  //提交
  save:function(newDataJson){
    var that = this
    var url = ''
    var data = {}
    switch (that.data.shopType) {
      case '0':
        url = '/admin_save_community_service_shop_content'
        data = {
          "id": app.globalData.shopId,
          "shop_name": newDataJson[0],
          "shop_phone": newDataJson[1],
          "gg": newDataJson[2],
          "address": newDataJson[3],
          "up_pay": newDataJson[4],
          "open_time": newDataJson[5],
          "close_time": newDataJson[6],
          "head_img": newDataJson[7],
        }
        break;
      case '1':
        url = '/admin_save_community_health_shop'
        data = {
          "id": app.globalData.shopId,
          "shop_name": newDataJson[0],
          "shop_phone": newDataJson[1],
          "address": newDataJson[2],
          "sheng": newDataJson[3][0],
          "shi": newDataJson[3][1],
          "content": newDataJson[4],
          "shop_img": newDataJson[5],
          "community_id": app.globalData.communityContent.community_id,
        }
        break;
      case '2':
        url = '/admin_save_community_service_kitchen_content'
        data = {
          "id": app.globalData.shopId,
          "name": newDataJson[0],
          "phone": newDataJson[1],
          "head_img": newDataJson[2],
        }
        break;
    }
    data = JSON.stringify(data);
    // console.log(data)
    util.postAjax(`${app.globalData.apiUrl}${url}`,function(res){
      // console.log(res)
      if(res.data == '1'){
        util.showToast('修改成功','success',2000)
        setTimeout(function(){
          wx.navigateBack({
            delta: 1, // 回退前 delta(默认为1) 页面
          })
          flag = false
        },500)
      }else{
        flag = false
        util.showToast('修改失败，请重新提交','none',2000)
      }
    },{pro: data})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})